package com.log4jviewer.ui.views;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.log4jviewer.Activator;
import com.log4jviewer.logfile.LogFileLoader;
import com.log4jviewer.ui.preferences.DefaultPreferences;

/**
 * Class handles press action on "Load log file" button. It gets logs from file and stores them to the model.
 * 
 * @author <a href="mailto:rd.ryly@gmail.com">Ruslan Diachenko</a>
 */
public class LogFileLoaderAction implements IViewActionDelegate {

    private static final String[] FILE_FILTER_EXT = { "*.log", "*.txt", "*" };

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private FileDialog fileDialog;

    private LogView logView;

    @Override
    public void run(final IAction action) {
        String selectedFile = fileDialog.open();
        logger.info("Log file: {} was selected.", selectedFile);

        try {
            if (selectedFile != null) {
                // Remove all logs from log list and log table before load new ones from log file.
                logView.getLogList().clear();
                logView.clearLogTable();

                // init log file pattern
                IPreferenceStore store = Activator.getInstance().getPreferenceStore();
                String logFilePattern = store.getString(DefaultPreferences.LogFilePreferences.getId());
                logger.debug("Log file pattern: {} was loaded.", logFilePattern);

                LogFileLoader logFileLoader = new LogFileLoader();
                logFileLoader.addListener(logView.getLogList());
                logFileLoader.load(selectedFile, logFilePattern);
                logFileLoader.removeListener(logView.getLogList());
            }
        } catch (FileNotFoundException e) {
            String errorMessage = "Log file wasn't found!";
            logView.getErrorManager().addError(errorMessage);
            logger.error(errorMessage, e);

        } catch (IOException e) {
            String errorMessage = "Error occured when reading or closing log file!";
            logView.getErrorManager().addError(errorMessage);
            logger.error(errorMessage, e);

        } catch (ParseException e) {
            String errorMessage = "Error occured when parsing the date format!";
            logView.getErrorManager().addError(errorMessage);
            logger.error(errorMessage, e);
        }
    }

    @Override
    public void selectionChanged(final IAction action, final ISelection selection) {
        // no code
    }

    @Override
    public void init(final IViewPart view) {
        logView = (LogView) view;

        // init file dialog
        fileDialog = new FileDialog(view.getSite().getShell(), SWT.OPEN);
        fileDialog.setText("Open log file");
        fileDialog.setFilterExtensions(FILE_FILTER_EXT);
        logger.info("File dialog was initialized.");
    }
}
